package com.yangjiayu.algorithm.binary_search;

public class Leetcode74 {
    //判断矩阵中是否存在一个目标值
    //已经排好序了

    public boolean searchMatrix(int[][] matrix, int target) {
        //先定义m和n
        int m = matrix.length;
        if(m==0) return false;
        int n = matrix[0].length;

        //二分查找，定义左右指针
        int left = 0;
        int right = m * n - 1; //最右端
        while( left <= right ){
            //计算中间位置
            int mid = left + (right - left) / 2;
            //计算二维矩阵中对应的行列号，取出对应元素
            int midElement = matrix[mid / n][mid % n];

            //判断中间元素与target的大小关系
            if(midElement == target){
                return true;
            }else if(midElement < target){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,60}};
        Leetcode74 leetcode74 = new Leetcode74();
        System.out.println(leetcode74.searchMatrix(matrix, 3));
    }

}
